package com.wf.smartcomm.server.job;


import java.math.BigDecimal;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.web.context.ContextLoaderListener;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wf.smartcomm.server.bean.Bill;
import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.service.BillService;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.PushUtils;


public class QuartzJobFactory implements Job {
	
	private static Logger logger = Logger.getLogger(QuartzJobFactory.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDetail detail = context.getJobDetail();
		UserService userService =(UserService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("userServiceImpl");
    	HouseService houseService =(HouseService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("houseServiceImpl");
    	VillageService villageService =(VillageService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("villageServiceImpl");
    	BillService billService = (BillService) ContextLoaderListener.getCurrentWebApplicationContext().getBean("billServiceImpl");
    	Village village = villageService.get(detail.getKey().getName());
    	List<House> houses = houseService.listToJobSchedule(village);
    	Long current = System.currentTimeMillis();
    	for (House house : houses) {
    		if (!StringUtils.isEmpty(house.getNotifyDate()) && house.getPrice() != null) {
    			List<Bill> bills = billService.listByHouse(house);
        		for (Bill bill : bills) {
        			Long toAt = Long.parseLong(bill.getToAt());
        			if (current >= toAt) {
        				bill.setType(ConstantUtils.BILL_TYPE_LOCKED);
        				billService.update(bill);
    				}
    			}
    			Long notifyDate = Long.parseLong(house.getNotifyDate());
    			if (current >= notifyDate) {
    				Bill bill = new Bill();
    				BigDecimal sum = house.getPrice().multiply(new BigDecimal(house.getArea())).multiply(new BigDecimal(village.getPeriod()));
    				bill.setPrice(sum);
    				bill.setHouse(house);
    				bill.setOrderCode("WY"+System.currentTimeMillis()+new Random().nextInt(999));
    				bill.setFromAt(house.getNotifyDate());
    				GregorianCalendar gc =new GregorianCalendar();
    				gc.setTimeInMillis(notifyDate);
    				gc.add(GregorianCalendar.MONTH, village.getPeriod());
    				bill.setToAt(String.valueOf(gc.getTimeInMillis()));
    				bill.setStatus(ConstantUtils.BILL_STATUS_CREATED);
    				bill.setType(ConstantUtils.BILL_TYPE_UNLOCKED);
    				billService.add(bill);
    				house.setNotifyDate(bill.getToAt());
    				houseService.update(house);
    				if (house.getUser() != null) {
    					String userId = house.getUser().getObjectId();
    					User user = userService.getUserById(userId);
    					Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    					try {
    						Pusher pusher = PushUtils.getClientPusher();
    						PushMessage msg = new PushMessage();
    	        			msg.setPushType(ConstantUtils.PUSH_TYPE_BILL_CREATED);
    	        			msg.setData(bill.getObjectId());
    	        			pusher.push0x20Message(user.getPushId().getBytes(), gson.toJson(msg).getBytes());
    						pusher.close();
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
    			}
    			logger.info("job scaner is excuted!!! job name is: "+detail.getKey().getGroup());
    		}
		}
	}

}
